package com.wr.async.Test;

// 死锁：多个线程都抱着对方需要的资源，然后形成僵持
// 目前未注释为死锁，注释的为解决方案
public class DeadLock {
    public static void main(String[] args) {
        new Thread(new MakeUp(0,"小红")).start();
        new Thread(new MakeUp(1,"小蓝")).start();
    }


}

// 镜子对象
class Mirror{

}

// 口红对象
class Lipstick{

}

// 化妆
class MakeUp implements Runnable{

    // 需要的资源都只有1分，用static
    static Mirror mirror = new Mirror();
    static Lipstick lipstick = new Lipstick();

    // 选择先获取哪个锁
    private int choose;
    // 线程名字
    private String name;

    @Override
    public void run() {
        try {
            makeUp(choose,name);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public MakeUp(int choose, String name) {
        this.choose = choose;
        this.name = name;
    }

    // 化妆方法
    public void makeUp(int choose,String name) throws InterruptedException {
        if (choose == 0){
            synchronized (mirror){
                System.out.println(name+"获得了镜子的锁");
                Thread.sleep(1000);
                // 解决方案为把口红锁拉出同步代码块
                synchronized (lipstick){
                    System.out.println(name+"获得了口红的锁");
                }
            }
//            synchronized (lipstick){
//                System.out.println(name+"获得了口红的锁");
//            }
        }else {
            synchronized (lipstick){
                System.out.println(name+"获得了口红的锁");
                Thread.sleep(1000);
                synchronized (mirror){
                    System.out.println(name+"获得了镜子的锁");
                }
            }
//            synchronized (mirror){
//                System.out.println(name+"获得了镜子的锁");
//            }
        }
    }
}